package com.sailmi.system.util;

import com.sailmi.system.config.DbConfig;
import jakarta.annotation.Resource;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.stereotype.Component;

import java.io.*;
import java.sql.*;
import java.util.Objects;

@Component
public class EnterpriseUtil {
	@Resource
	DbConfig dbConfig;
	private static Logger log = LoggerFactory.getLogger(EnterpriseUtil.class);
	public boolean genEn(String enCode) throws SQLException, IOException {
		genDb(enCode);
		genNacosConfig(enCode);
		return false;
	}
	private Connection getConnect(String dbName){
		Connection connection = null;
		if(Objects.nonNull(dbConfig.getBizDbDriver())
			&&Objects.nonNull(dbConfig.getBizDbUrl())
			&&Objects.nonNull(dbConfig.getBizDbUser())
			&&Objects.nonNull(dbConfig.getBizDbPassword())){
			try {
				connection = DriverManager.getConnection(
					dbConfig.getBizDbUrl()+"/"+dbName,
					dbConfig.getNacosDBUser(),
					dbConfig.getNacosDbPassword());
			} catch (SQLException e) {
				throw new RuntimeException(e);
			}
		}
		return connection;
	}
	private void genDb(String enCode) throws SQLException, IOException {
		String modelDbName = "EN_"+enCode+"_MODEL";
		String bizDbName = "EN_"+enCode+"_BIZ";
		String modelDbSql = "CREATE DATABASE "+modelDbName+" CHARACTER SET utf8mb4 COLLATE utf8mb4_general_ci;";
		String bizDbSql = "CREATE DATABASE "+bizDbName+" CHARACTER SET utf8mb4 COLLATE utf8mb4_general_ci;";
		Connection connection = getConnect(dbConfig.getSysDbName());
		if(Objects.nonNull(connection)){
			//创建业务库
			PreparedStatement psBiz = connection.prepareStatement(bizDbSql);
			psBiz.execute();
			psBiz.close();
			//创建模型库
			PreparedStatement psModel = connection.prepareStatement(modelDbSql);
			psModel.execute();
			psModel.close();
			connection.close();
			//生成模型库中的表
			genModelTable(modelDbName);
		}

	}

	private void genModelTable(String modelDbName) throws IOException, SQLException {
		Connection connection = getConnect(modelDbName);
		String filePath = "model_table.sql";
		FileInputStream fis = new FileInputStream(filePath);
		BufferedReader reader = new BufferedReader(new InputStreamReader(fis));
		StringBuilder sb = new StringBuilder();
		String line;
		while ((line = reader.readLine()) != null) {
			sb.append(line).append("\n");
		}
		reader.close();
		fis.close();
		String sqlScript = sb.toString();
		Statement stmt = connection.createStatement();
		String[] statements = sqlScript.split(";");
		for (String statement : statements) {
			if (!statement.trim().isEmpty()) { // 确保语句非空
				log.info("导入SqL:"+statement);
				stmt.execute(statement);
			}
		}
		stmt.close();
		connection.close();
	}

	private void genNacosConfig(String enCode){

	}
}
